import express from 'express'
import expressWebSocket from 'express-ws'

let wsInstance

function localServer() {
    let app = express()
    if (!wsInstance)
        wsInstance = expressWebSocket(app, null, {
            perMessageDeflate: true
        })
    app.ws('/ws', rtspRequestHandle)
    app.listen(8801)
    console.log('express listened')
}

const sendSuffix = ''

function rtspRequestHandle(ws, req) {
    let url = req.query.url
    console.log('连接地址参数url:', url)

    const send = (str) => {
        ws.send(str + sendSuffix)
    }

    // const wsServer = wsInstance.getWss();
    // console.log(wsServer.clients);

    // these should be detected from the source stream
    // const [width, height] = [0, 0];
    // const streamHeader = Buffer.alloc(8);
    // streamHeader.write('jsmp');
    // streamHeader.writeUInt16BE(width, 4);
    // streamHeader.writeUInt16BE(height, 6);
    // ws.send(streamHeader, { binary: true });
    ws.on('message', function (msg) {
        const sp = msg.split(sendSuffix).filter((el) => el.length > 0)
        for (let i = 0; i < sp.length; i++) {
            const el = sp[i]
            console.log('收到消息', el)
            if ('~' === el) {
                send('~')
            }
        }
    })
    ws.send('data')

    ws.on('close', () => {})
}

localServer()
